package com.chinacoal.microservice.impl.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.api.OrgOpenClient;
import com.chinacoal.microservice.exception.MessageException;
import com.chinacoal.microservice.impl.mapper.AgentMapper;
import com.chinacoal.microservice.impl.service.AgentService;
import com.chinacoal.microservice.impl.util.CommonFun;
import com.chinacoal.microservice.model.organization.vo.EmployeeVO;
import com.chinacoal.microservice.model.wofkflow.QueryAgentParam;
import com.chinacoal.microservice.model.wofkflow.entity.AgentEntity;
import com.chinacoal.microservice.model.wofkflow.entity.AgentItemEntity;
import com.chinacoal.microservice.model.wofkflow.resource.WrapAttribute;
import com.chinacoal.microservice.util.result.Result;
import com.chinacoal.microservice.util.tool.Tool;
import com.eos.workflow.api.IBPSServiceClient;
import com.eos.workflow.data.WFAgentItem;
import com.eos.workflow.omservice.WFParticipant;

/**  
 * @Package: com.chinacoal.microservice.impl.service.impl.AgentServiceImpl
 * @ClassName: AgentServiceImpl
 * @ClassDesc: 审批代理ServiceImpl
 * @Createby: sunh
 * @CreatedDate: 2019-11-29 10:14:51
 */  
@Service("AgentService")
public class AgentServiceImpl implements AgentService {
	
	@Resource
	private AgentMapper agentMapper;
	@Resource
	private OrgOpenClient orgOpenClient;
	
	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public Page<AgentEntity> findList(int page, int pageSize, QueryAgentParam param) throws Exception {

		Page<AgentEntity> agentPage = CommonFun.getPage(page, pageSize);
		
		List<AgentEntity> ageentList = agentMapper.findList(agentPage, param);
		
		return agentPage.setRecords(ageentList);
	}
	
	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public AgentEntity findOne(Long agentId) throws Exception{
		
		// 查询代理信息
		AgentEntity agentEntity = agentMapper.findOne(agentId);
		
		List<WrapAttribute> agentToList = new ArrayList<WrapAttribute>();
		WrapAttribute wrapAttribute = new WrapAttribute();
		wrapAttribute.setId(agentEntity.getAgentTo());
		wrapAttribute.setName(agentEntity.getAgentToName());
		agentToList.add(wrapAttribute);
		agentEntity.setAgentToList(agentToList);
		
		// 查询代理行信息
		List<AgentItemEntity> agentItemList = agentMapper.getAgentItemList(agentId);
		
		agentEntity.setAgentItemList(agentItemList);
		
		return agentEntity;
		
	}
	
	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void insertAgent(IBPSServiceClient client, AgentEntity agentEntity) throws Exception{
		
		// 参数整理
		String agentFromId = getEmpByUserId(agentEntity.getUserId()).toString();
		WFParticipant[] agentTo = null;
		String agentType = agentEntity.getAgentType();
		Date startTime = Tool.getStartDate(agentEntity.getStartTime(), Tool.CALENDAR_DAY);
		Date endTime = Tool.getEndDate(agentEntity.getEndTime(), Tool.CALENDAR_DAY);
		WFAgentItem[] agentItem = null;
		String agentReason = agentEntity.getAgentReason();
		
		// 代理人
		List<WrapAttribute> agentToList = agentEntity.getAgentToList();
		if(agentToList != null && agentToList.size() > 0) {
			agentTo = new WFParticipant[agentToList.size()];
			for (int i = 0; i < agentToList.size(); i++) {
				WrapAttribute attribute = agentToList.get(i);
				String empId = getEmpByUserId(Tool.toInteger(attribute.getId())).toString();
				agentTo[i]= new WFParticipant(empId,attribute.getName(),"emp");
			}
		}
		
		// 流程列表
		List<AgentItemEntity> agentItemList = agentEntity.getAgentItemList();
		if(agentItemList != null && agentItemList.size() > 0) {
			agentItem = new WFAgentItem[agentItemList.size()];
			for (int i = 0; i < agentItemList.size(); i++) {
				AgentItemEntity agentItemEntity = agentItemList.get(i);
				
				WFAgentItem wfAgentItem = new WFAgentItem();
				String itemType = Tool.nvl(agentItemEntity.getItemType(), "").toUpperCase();
				wfAgentItem.setItemID(agentItemEntity.getItemId());
				wfAgentItem.setAccessType(agentItemEntity.getAccessType());
				wfAgentItem.setItemType(itemType);
				
				agentItem[i] = wfAgentItem;
			}
		}
		
		// 执行新增
		List <Long> agentIdList = client.getAgentManager().createAgent(agentFromId, agentTo, agentType, startTime, endTime, agentItem, agentReason);
		
		// 更新流程列表的所属流程
		if(agentIdList != null && agentItemList != null && agentItemList.size() > 0) {
			Long agentId = agentIdList.get(0);
			for (AgentItemEntity agentItemEntity : agentItemList) {
				if(StringUtils.isEmpty(agentItemEntity.getItemName())) continue;
				agentItemEntity.setAgentId(agentId);
				agentMapper.updateAgentItem(agentItemEntity);
			}
		}
	}
	
	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void updateAgent(IBPSServiceClient client, AgentEntity agentEntity) throws Exception{
		
		if(agentEntity.getAgentId() == null) throw new MessageException("更新时主键id不能为空: agentId");
		
		// 参数整理
		Long agentId = agentEntity.getAgentId();
		String agentFromId = getEmpByUserId(agentEntity.getUserId()).toString();
		WFParticipant agentTo = null;
		Date startTime = Tool.getStartDate(agentEntity.getStartTime(), Tool.CALENDAR_DAY);
		Date endTime = Tool.getEndDate(agentEntity.getEndTime(), Tool.CALENDAR_DAY);
		WFAgentItem[] agentItem = null;
		String agentReason = agentEntity.getAgentReason();
		
		// 代理人
		List<WrapAttribute> agentToList = agentEntity.getAgentToList();
		if(agentToList != null && agentToList.size() > 0) {
			WrapAttribute attribute = agentToList.get(0);
			String empId = getEmpByUserId(Tool.toInteger(attribute.getId())).toString();
			agentTo = new WFParticipant(empId,attribute.getName(),"emp");
		}
		
		// 流程列表
		List<AgentItemEntity> agentItemList = agentEntity.getAgentItemList();
		if(agentItemList != null && agentItemList.size() > 0) {
			agentItem = new WFAgentItem[agentItemList.size()];
			for (int i = 0; i < agentItemList.size(); i++) {
				AgentItemEntity agentItemEntity = agentItemList.get(i);
				
				WFAgentItem wfAgentItem = new WFAgentItem();
				String itemType = Tool.nvl(agentItemEntity.getItemType(), "").toUpperCase();
				wfAgentItem.setItemID(agentItemEntity.getItemId());
				wfAgentItem.setAccessType(agentItemEntity.getAccessType());
				wfAgentItem.setItemType(itemType);
				
				agentItem[i] = wfAgentItem;
			}
		}
		
		// 执行修改
		client.getAgentManager().modifyAgent(agentId,agentFromId,agentTo,startTime,endTime,agentReason);
		client.getAgentManager().modifyAgentItem(agentId,"SET",agentItem);
		
		// 更新流程列表的所属流程
		if(agentItemList != null && agentItemList.size() > 0) {
			for (AgentItemEntity agentItemEntity : agentItemList) {
				if(StringUtils.isEmpty(agentItemEntity.getItemName())) continue;
				agentMapper.updateAgentItem(agentItemEntity);
			}
		}
	}
	
	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void deleteAgent(IBPSServiceClient client, Long agentId) throws Exception{
		
		client.getAgentManager().deleteAgentBatch(new long[] {agentId});
	}
	
	@Override
	@Transactional(isolation=Isolation.READ_COMMITTED,propagation=Propagation.REQUIRED,rollbackFor={Exception.class})
	public void deleteAgentItem(Long agentItemId) throws Exception{
		agentMapper.deleteAgentItem(agentItemId);
	}
	
	/**  
	 * @Package: com.chinacoal.microservice.impl.service.impl.WorkFlowServiceImpl.getEmpByUserId
	 * @MethodName: getEmpByUserId
	 * @MethodDesc: 获取员工Id
	 * @ParamList: {
	 *				 @param userId
	 *			   }
	 * @Return: Integer
	 * @Createby: sunh
	 * @CreatedDate: 2019-12-03 15:20:09
	 */ 
	private Integer getEmpByUserId(Integer userId) throws Exception{
		
		Result<EmployeeVO> empResult = orgOpenClient.getEmpDetial(userId, null);
		if(empResult == null || empResult.getData() == null || empResult.getData().getEmpId() == null) {
			throw new MessageException("当前用户没有对应的员工");
		}
		
		Integer empId = empResult.getData().getEmpId();
		
		return Tool.toInteger(empId.toString());
	}
}
